import axios from 'axios'
import useUserStore from '../store/userStore'
import router from '../router'
import { ElMessage } from 'element-plus'

const http = axios.create({
  baseURL: 'http://47.105.62.192:3000/',
})

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 禁用缓存
    config.headers['Cache-Control'] = 'no-cache'
    config.headers['Pragma'] = 'no-cache'
    // 添加 token
    if (config.url !== '/login/phone' && !config.url.startsWith('/getCode/'))
      config.headers.Authorization = useUserStore().token
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截器
http.interceptors.response.use(
  (response) => {
    return response.data
  },
  // 响应错误拦截器
  (error) => {
    // 401 跳转登录页
    if (error.status === 401) {
      router.push('/login')
      useUserStore().$reset()
      ElMessage.error('登录已过期，请重新登录')
    }
    return Promise.reject(error)
  }
)
export default http
